package com.vecspace.msoffice;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class XSSFSheetCells {
	
	List<MergeRegion> mergeRegions = new ArrayList<>();
	XSSFSheet sheet;
	
	public XSSFSheetCells(XSSFSheet sheet) {
		readAllMergeRegions(sheet);
	}
	
	private void readAllMergeRegions(XSSFSheet sheet) {
		this.sheet = sheet;
		int mergedRegionsCount = sheet.getNumMergedRegions();
		for(int i=0; i<mergedRegionsCount; ++i) {
			CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
			MergeRegion	mergedRegion = new MergeRegion(cellRangeAddress.getFirstRow(), cellRangeAddress.getLastRow(),
					cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
			XSSFRow row = sheet.getRow(cellRangeAddress.getFirstRow());
			XSSFCell cell = row.getCell(cellRangeAddress.getFirstColumn());
			Object cellValue = POIUtil.getCellValue(cell);
			mergedRegion.setCellValue(cellValue);
			mergeRegions.add(mergedRegion);
		}		
	}
	
	/**读取单元格的值。如果处于合并单元格中，则返回第一个单元格的值。
	 * 
	 * @param rownum
	 * @param colnum
	 * @return 
	 * @author: wanghua
	 */
	public CellValue getCellValue(int rownum, int colnum) {
		CellValue cellValue = new CellValue(rownum, colnum);
		boolean isMergeRegion = false;
		for(int i=0; i<mergeRegions.size(); ++i) {
			MergeRegion mergeRegion = mergeRegions.get(i);
			if(mergeRegion.contains(rownum, colnum)) {
				isMergeRegion = true;
				cellValue.setValue(mergeRegion.getCellValue());
				cellValue.setMergedCell(true);
				if(mergeRegion.getStartRow() == rownum && mergeRegion.getStartCol() == colnum) {
					cellValue.setMergeReginFirsetCell(false);
				}else {
					cellValue.setMergeReginFirsetCell(true);
				}
			}
		}
		if(!isMergeRegion) {
			XSSFRow row = sheet.getRow(rownum);
			XSSFCell cell = row.getCell(colnum);
			cellValue.setValue(POIUtil.getCellValue(cell));
		}
		
		return cellValue;
	}
	
	/**读取单元格的值。如果处于合并单元格中，则返回第一个单元格的值。
	 * 保证不会返回null，但是会返回""，
	 * @param rownum
	 * @param colnum
	 * @return 
	 * @author: wanghua
	 */
	public String getCellText(int rownum, int colnum) {
		CellValue cell = this.getCellValue(rownum, colnum);
		if(cell == null) return "";
		String text = cell.getStringValue();
		if(text == null) return "";
		return text;
	}
}
